package com.totoro.tygeneratedragonblock.executor.condition.impl;

import com.totoro.tygeneratedragonblock.constants.ConditionConst;
import com.totoro.tygeneratedragonblock.constants.StaticSystemVarConst;
import com.totoro.tygeneratedragonblock.data.ConditionResult;
import com.totoro.tygeneratedragonblock.executor.condition.ConditionExecutor;
import com.totoro.tygeneratedragonblock.utils.ColorUtil;
import com.totoro.tygeneratedragonblock.utils.JexlUtil;
import com.totoro.tygeneratedragonblock.utils.PapiUtil;
import com.totoro.tygeneratedragonblock.utils.StrUtil;
import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlExpression;
import org.apache.commons.jexl3.MapContext;
import org.bukkit.entity.Player;

public class PapiConditionExecutor implements ConditionExecutor {
    @Override
    public ConditionResult execute(String condition, Player player) {
        String[] split = condition.split("<>");
        String failReason = null;
        if(split.length == 2) {
            condition = split[0];
            failReason = split[1];
        }
        ConditionResult conditionResult = new ConditionResult(false, failReason);
        condition = StrUtil.getPrefixAfter(condition, ConditionConst.PAPI_CONDITION);
        String conditionText = getFinalConditionText(condition);
        if(StaticSystemVarConst.dependentPlaceholderEnable) {
            conditionText = ColorUtil.cleanColor(PapiUtil.parseStrPapiVariable(player, conditionText, true));
        }
        try {
            Object result = JexlUtil.evaluateExpressions(conditionText);
            if (result instanceof Boolean) {
                conditionResult.setIsSuccess((Boolean) result);
                return conditionResult;
            }
            return conditionResult;
        } catch (Exception e) {
            e.printStackTrace();
            return conditionResult;
        }
    }
}
